package com.zxl.always.on.display.configs.sdk;


import com.zxl.always.on.display.ApplicationHelper;
import com.zxl.always.on.display.tools.FileUtil;
import com.zxl.always.on.display.tools.MachineUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Locale;

/**
 * Created by Administrator on 2018/2/13.
 */

public class OnlineConfigAgent implements Runnable {

    private String mAppKey, mChannel;

    private static OnlineConfigAgent sInstance;

    private OnlineConfigureListener mOnlineConfigureListener;

    private String cachePath;

    private JSONObject mCacheJSONObject;

    private OnlineConfigAgent() {
        cachePath = new File(ApplicationHelper.getContext().getCacheDir(), "config_" + MachineUtils.getCurrProcessName(ApplicationHelper.getContext())).getPath();
    }

    public static OnlineConfigAgent getInstance() {
        if (null == sInstance) {
            sInstance = new OnlineConfigAgent();
        }
        return sInstance;
    }

    public void init(String appKey, String channel) {
        this.mAppKey = appKey;
        this.mChannel = channel;
    }


    public void updateOnlineConfig(OnlineConfigureListener mOnlineConfigureListener) {
        this.mOnlineConfigureListener = mOnlineConfigureListener;
        new Thread(this).start();
    }

    public String getConfigParams(String key) {
        if (null != mCacheJSONObject) {
            return mCacheJSONObject.optString(key);
        } else {
            if (FileUtil.isFileExist(cachePath)) {
                try {
                    mCacheJSONObject = new JSONObject(FileUtil.readFileToString(cachePath));
                    return mCacheJSONObject.optString(key);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    @Override
    public void run() {
        byte[] bs = ConfigDataHelper.doPost(mAppKey, mChannel);
        if (null != bs && bs.length > 0) {
            try {
                JSONObject jsonObject = new JSONObject(new String(bs));
                if(!jsonObject.has("config_update") || jsonObject.getString("config_update").toLowerCase(Locale.US).equals("no")) {
                    return;
                }
                JSONObject params = jsonObject.optJSONObject("online_params");
                if (null != params) {
                    mCacheJSONObject = params;
                    FileUtil.saveByteToSDFile(bs, cachePath);
                    if (null != mOnlineConfigureListener) {
                        mOnlineConfigureListener.onDataReceived(params);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }



}
